package hell.p2p.base;

import java.io.IOException;
import java.net.ServerSocket;


public class TCPServer implements Runnable {
    private ServerSocket server;
    private int port;
    private boolean active;


    public TCPServer(int port)
    {
        this.port=port;
        active = false;


    }

    public boolean init(){

        try {
            server = new ServerSocket(port);
            active=true;
            Thread local = new Thread(this);
            local.start();
            return true;

        } catch (IOException e) {
            System.out.println("error starting server");
        }

        return false;

    }

    public void stop(){

        active=false;

    }

    public TCPClient accept() throws IOException {


        return new TCPClient(server.accept());
    }


    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        if(!active){
            this.port = port;
        }
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    @Override
    public void run() {
        while (active){
            try {
                TCPClient accepted = this.accept();
            } catch (IOException e) {
                System.out.println("Socket closed");
            }
        }
    }
}
